////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// The MIT License (MIT)                                                      //
//                                                                            //
// Copyright (c) 2013 Charles Teague                                          //
//                                                                            //
// Permission is hereby granted, free of charge, to any person obtaining a    //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation  //
// the rights to use, copy, modify, merge, publish, distribute, sublicense,   //
// and/or sell copies of the Software, and to permit persons to whom the      //
// Software is furnished to do so, subject to the following conditions:       //
//                                                                            //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software.                        //
//                                                                            //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING    //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER        //
// DEALINGS IN THE SOFTWARE.                                                  //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Security.Cryptography;

using RPSDAL;
using RPSDAL.CollectionClasses;
using RPSDAL.FactoryClasses;
using RPSDAL.HelperClasses;
using RPSDAL.DaoClasses;
using RPSDAL.EntityClasses;
using RPSDAL.RelationClasses;

using SD.LLBLGen.Pro.ORMSupportClasses;


public partial class Contact : System.Web.UI.Page
{
    #region initialize page

    protected override void OnInit(System.EventArgs e)
    {
        if (Parameters.LoggedUser != -1) 
        {
            UserEntity eUser = new UserEntity(Parameters.LoggedUser);
            RoleEntity eRole = new RoleEntity(eUser.RoleId);

            
            if (!eRole.HasEditContact) 
            {
                Parameters.LoggedUser = -1;
                Response.Redirect("Default.aspx");
                return;
            }
        }


        LoadContactTypes();
        LoadStates();
        LoadCountries();
    }

    #region load states

    private void LoadStates() 
    {
        try
        {
            DataSet ds = new DataSet();
            ds.ReadXml(Methods.AppRoot+"\\Data\\states.xml");
            cmbStates.DataSource = ds.Tables[0];
            cmbStates.DataTextField = ds.Tables[0].Columns[0].ColumnName;
            cmbStates.DataValueField = ds.Tables[0].Columns[0].ColumnName;
            cmbStates.DataBind();           
        }
        catch { }
    }

    #endregion load states

    #region load countries

    private void LoadCountries()
    {
        try
        {
            DataSet ds = new DataSet();
            ds.ReadXml(Methods.AppRoot + "\\Data\\countries.xml");
            cmbCountry.DataSource = ds.Tables[0];
            cmbCountry.DataTextField = ds.Tables[0].Columns[0].ColumnName;
            cmbCountry.DataValueField = ds.Tables[0].Columns[0].ColumnName;
            cmbCountry.DataBind();
        }
        catch { }
    }

    #endregion load countries

    #region load contact types

    /// <summary>
    /// load contact types
    /// </summary>
    private void LoadContactTypes()
    {

        // load contact types
        ContactTypeCollection cContactTypes = new ContactTypeCollection();
        cContactTypes.GetMulti(null);

        cmbContactTypes.DataSource = cContactTypes;
        cmbContactTypes.DataTextField = ContactTypeFields.Name.Name;
        cmbContactTypes.DataValueField = ContactTypeFields.ContactTypeId.Name;
        cmbContactTypes.DataBind();

        if (cContactTypes.Count <= 0)
        {
            // no contact types defined show error message
        }
        else
        {
            int contactTypeId = Convert.ToInt32(Request.Form["ctl00$ContentPlaceHolder1$cmbContactTypes"]);
            if (Request.QueryString["id"] != null)
            {
                int contactId = Convert.ToInt32(Global.DecryptString(Request.QueryString["id"].ToString()));
                ContactEntity eContact = new ContactEntity(contactId);
                cmbContactTypes.SelectedValue = eContact.ContactTypeId.ToString();                
            }
             
            if (cmbContactTypes.SelectedIndex > 0)
            {
                contactTypeId = Convert.ToInt32(cmbContactTypes.SelectedValue);
            }

            if (contactTypeId == 0) 
            {
                contactTypeId = cContactTypes[0].ContactTypeId;
            }

            ShowExtraFields(contactTypeId);
        }
    }

    #endregion load contact types

    #region load contact files

    private void LoadFiles(int contactId) 
    {
        ContactFileCollection cContactFiles = new ContactFileCollection();
        IPredicateExpression filter = new PredicateExpression();
        filter.Add(ContactFileFields.ContactId == contactId);
        cContactFiles.GetMulti(filter);

        grdContactFiles.DataSource = cContactFiles;
        grdContactFiles.DataBind();
    }

    #endregion load contact files

  
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) 
        {
            try
            {
                btnAddFiles.Attributes.Add("OnClick", "return AddAttachmentControls()");

                if (Request.QueryString["id"] != null)
                {
                    int contactId = Convert.ToInt32(Global.DecryptString(Request.QueryString["id"].ToString()));
                    ContactEntity eContact = new ContactEntity(contactId);                    

                    // load default values
                    txtName.Text = eContact.Name;
                    txtMail.Text = eContact.EmailAddress;
                    txtPhone.Text = eContact.Phone;
                    txtMobile.Text = eContact.MobilePhone;
                    txtMailAddress.Text = eContact.MailAddress;
                    txtMailCity.Text = eContact.MailCity;
                    cmbStates.SelectedValue = eContact.MailState;
                    cmbCountry.SelectedValue = eContact.MailCountry;
                    txtZip.Text = eContact.MailZip;
                    txtVisitDate.Text = eContact.ContactVisitDate.ToString("MM/dd/yyyy");
                    txtFax.Text = eContact.Fax;
                    ckActive.Checked = eContact.Active;
                    ckReceiveNewsLetter.Checked = eContact.SendNewsletter;

                    // load extra values
                    ContactFieldCollection cContactField = new ContactFieldCollection();
                    IPredicateExpression filter = new PredicateExpression();
                    filter.Add(ContactFieldFields.ContactId == eContact.ContactId);
                    cContactField.GetMulti(filter);

                    for (int i = 0; i < cContactField.Count; i++) 
                    { 
                        for (int j=0; j< grdFields.Rows.Count; j++)
                        {

                            if (Convert.ToInt32(((TextBox)grdFields.Rows[j].Cells[1].FindControl("id")).Text) == 
                                cContactField[i].ContactPageFieldId)
                            {
                                switch (Convert.ToInt32(grdFields.Rows[j].Cells[1].Text)) 
                                {
                                    case Parameters.TEXTBOX_TYPE:
                                    case Parameters.DATETIME_TYPE:
                                    case Parameters.TEXTAREA_TYPE:
                                        ((TextBox)grdFields.Rows[j].Cells[1].Controls[0]).Text = cContactField[i].FieldValue;
                                        break;
                                    case Parameters.COMBOBOBOX_TYPE:
                                        ((DropDownList)grdFields.Rows[j].Cells[1].Controls[0]).SelectedValue = cContactField[i].FieldValue;
                                        break;
                                    case Parameters.CHECKBOX_TYPE:
                                        ((CheckBox)grdFields.Rows[j].Cells[1].Controls[0]).Checked = 
                                            cContactField[i].FieldValue.ToUpper() == "TRUE" ? true : false ;
                                        break;
                                }
                            }
                        }
                    }

                    // load files
                    LoadFiles(contactId);
                    LoadContactGroups(contactId);
                }
            }
            catch { }
        }
    }

    /// <summary>
    /// load all contacts into the contact list
    /// </summary>
    private void LoadContactGroups(int contactId)
    {
        ContactGroupMemberCollection cContactGroupMember = new ContactGroupMemberCollection();
        IPredicateExpression filter = new PredicateExpression();
        filter.Add(ContactGroupMemberFields.ContactId == contactId);
        cContactGroupMember.GetMulti(filter);

        filter = new PredicateExpression();
        for (int i = 0; i < cContactGroupMember.Count; i++) 
        {
            filter.AddWithOr(ContactGroupFields.ContactGroupId == cContactGroupMember[i].ContactGroupId);
        }

        ContactGroupCollection cContactGroups = new ContactGroupCollection();
        cContactGroups.GetMulti(filter);

        grdContactGroups.DataSource = cContactGroups;
        grdContactGroups.DataBind();
        grdContactGroups.Visible = true;

        if (Parameters.LoggedUser != -1)
        {
            UserEntity eUser = new UserEntity(Parameters.LoggedUser);
            RoleEntity eRole = new RoleEntity(eUser.RoleId);

            if (!eRole.HasEditContactGroup)
            {
                grdContactGroups.Columns[2].Visible = false;
                grdContactGroups.Columns[3].Visible = false;
            }
        }
    }

    #region load extra contact type fields

    /// <summary>
    /// load fields to be filled in for a given contact type
    /// </summary>
    /// <param name="contactTypeId"></param>
    private void ShowExtraFields(int contactTypeId)
    {

        // load contact type fields
        DataTable dtFields = Fields(contactTypeId);
        grdFields.DataSource = dtFields;
        grdFields.DataBind();

        for (int i = 0; i < grdFields.Rows.Count; i++)
        {
            try
            {
                switch (Convert.ToInt32(grdFields.Rows[i].Cells[1].Text))
                {
                    case Parameters.TEXTBOX_TYPE:
                        //textbox
                        TextBox txtTextBox = new TextBox();
                        txtTextBox.Width = new Unit(60, UnitType.Percentage);
                        grdFields.Rows[i].Cells[1].Controls.Add(txtTextBox);
                        break;
                    case Parameters.COMBOBOBOX_TYPE:
                        // combobox
                        ContactPageDropdownFieldValueCollection cComboboxValues = new ContactPageDropdownFieldValueCollection();
                        IPredicateExpression filter = new PredicateExpression();
                        filter.Add(ContactPageDropdownFieldValueFields.ContactPageFieldId == Convert.ToInt32(((TextBox)grdFields.Rows[i].Cells[1].FindControl("id")).Text));
                        cComboboxValues.GetMulti(filter);

                        DropDownList cmbComboBox = new DropDownList();
                        cmbComboBox.DataSource = cComboboxValues;
                        cmbComboBox.DataValueField = ContactPageDropdownFieldValueFields.Value.Name;
                        cmbComboBox.DataTextField = ContactPageDropdownFieldValueFields.Value.Name;
                        cmbComboBox.DataBind();

                        cmbComboBox.Width = new Unit(60, UnitType.Percentage);
                        grdFields.Rows[i].Cells[1].Controls.Add(cmbComboBox);
                        break;
                    case Parameters.CHECKBOX_TYPE:
                        CheckBox ckCehckBox = new CheckBox();
                        grdFields.Rows[i].Cells[1].Controls.Add(ckCehckBox);
                        break;
                    case Parameters.TEXTAREA_TYPE:
                        TextBox txtTextArea = new TextBox();
                        txtTextArea.TextMode = TextBoxMode.MultiLine;
                        txtTextArea.Columns = Convert.ToInt32(dtFields.Rows[i][6]);
                        txtTextArea.Rows = Convert.ToInt32(dtFields.Rows[i][5]);
                        grdFields.Rows[i].Cells[1].Controls.Add(txtTextArea);
                        break;
                    case Parameters.DATETIME_TYPE:
                        TextBox txtDateTime = new TextBox();
                        txtDateTime.ID = "txtDateTimeId";
                        grdFields.Rows[i].Cells[1].Controls.Add(txtDateTime);
                        Image imgDateTime = new Image();
                        imgDateTime.ImageUrl = "jscripts/date/calendar.gif";
                        imgDateTime.ID = "dateId";
                        grdFields.Rows[i].Cells[1].Controls.Add(imgDateTime);
                        break;
                }
            }
            catch { }

        }
    }

    #endregion load extra contact type fields


    #endregion initialize page

    #region user interface


    /// <summary>
    /// treat edit/ remove commands
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Command(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Page")
        {
            return;
        }
        if (((System.Web.UI.WebControls.Button)(e.CommandSource)).Text == "Edit")
        {
            Global.UserLogSave(Parameters.LoggedUser, "Edit Contact Group id=" + e.CommandArgument.ToString());
            Response.Redirect("ContactGroup.aspx?id=" + Global.EncryptString(e.CommandArgument.ToString()));
        }
        else
        {
            // remove contact group

            Global.UserLogSave(Parameters.LoggedUser, "Remove Contact Group id=" + e.CommandArgument.ToString());

            int contactGroupId = Convert.ToInt32(e.CommandArgument);
            ContactGroupEntity eContactGroup = new ContactGroupEntity(contactGroupId);

            // delete business rules for this contact group
            BusinessRuleCollection cBusinessRules = new BusinessRuleCollection();
            IPredicateExpression filter = new PredicateExpression();
            filter.Add(BusinessRuleFields.ContactGroupId == eContactGroup.ContactGroupId);
            cBusinessRules.GetMulti(filter);

            for (int i = 0; i < cBusinessRules.Count; i++)
            {
                LetterCollection cLetters = new LetterCollection();
                IPredicateExpression filterLetter = new PredicateExpression();
                filterLetter.Add(LetterFields.BusinessRulesId == cBusinessRules[i].BusinessRuleId);
                cLetters.DeleteMulti(filterLetter);

                CallCollection cCalls = new CallCollection();
                IPredicateExpression filterCall = new PredicateExpression();
                filterCall.Add(CallFields.BusinessRuleId == cBusinessRules[i].BusinessRuleId);
                cCalls.GetMulti(filterCall);

                for (int j = 0; j < cCalls.Count; j++)
                {
                    CallFinishedValueCollection cCallFinishedValues = new CallFinishedValueCollection();
                    IPredicateExpression filterCallFinishedValue = new PredicateExpression();
                    filterCallFinishedValue.Add(CallFinishedValueFields.CallId == cCalls[j].CallId);
                    cCallFinishedValues.DeleteMulti(filterCallFinishedValue);
                }

                cCalls.DeleteMulti(filterCall);
            }

            cBusinessRules.DeleteMulti(filter);

            // delete group members
            ContactGroupMemberCollection cContactGroupMembers = new ContactGroupMemberCollection();
            IPredicateExpression filterContactGroupMember = new PredicateExpression();
            filterContactGroupMember.Add(ContactGroupMemberFields.ContactGroupId == eContactGroup.ContactGroupId);
            cContactGroupMembers.DeleteMulti(filterContactGroupMember);

            eContactGroup.Delete();

            Response.Redirect("ContactGroupList.aspx");
        }
    }

    /// <summary>
    /// attach javascript actions to grid view buttons
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Button button = (Button)e.Row.FindControl("btnRemove");
            button.Attributes.Add("onclick", @"javascript:return confirm('Are you sure you want to delete this contact group? This will delete everything related to it (business rules, letters etc.). ');");
        }
    }

    /// <summary>
    /// add new contact group
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void AddNewContactGroup(object sender, EventArgs e)
    {
        Global.UserLogSave(Parameters.LoggedUser, "Add New Contact Group");
        Response.Redirect("ContactGroup.aspx");
    }

    protected void grdContactGroups_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdContactGroups.PageIndex = e.NewPageIndex;

        if (Request.QueryString["id"] != null)
        {
            int contactId = Convert.ToInt32(Global.DecryptString(Request.QueryString["id"].ToString()));
            LoadContactGroups(contactId);
        }
    }


    /// <summary>
    /// cancel add new contact
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Cancel(object sender, EventArgs e)
    {
        Response.Redirect("ContactList.aspx");
    }

    

    /// <summary>
    /// insert or update contact
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Save(object sender, EventArgs e)
    {
        if (!Page.IsValid)
        {
            return;
        }

        Global.UserLogSave(Parameters.LoggedUser, "Save Contact");
        ContactEntity eContact = new ContactEntity();
        bool isNew = true;
        if (Page.IsPostBack && !String.IsNullOrEmpty(Request.QueryString["id"])) 
        {
            eContact = new ContactEntity(Convert.ToInt32(Global.DecryptString(Request.QueryString["id"].ToString())));
            ContactFieldCollection cContactField = new ContactFieldCollection();
            IPredicateExpression filter = new PredicateExpression();
            filter.Add(ContactFieldFields.ContactId == eContact.ContactId);
            cContactField.DeleteMulti(filter);
            isNew = false;
        }

        try
        {
            eContact.ContactTypeId = Convert.ToInt32(cmbContactTypes.SelectedValue);
        }
        catch { }
        eContact.Name = txtName.Text;
        eContact.EmailAddress = txtMail.Text;
        eContact.MailAddress = txtMailAddress.Text;
        eContact.MailState = cmbStates.SelectedValue == "Choose a state..." ? "" : cmbStates.SelectedValue;
        eContact.MailCity = txtMailCity.Text;
        eContact.MailZip = txtZip.Text;
        eContact.MailCountry = cmbCountry.SelectedValue;
        eContact.Phone = txtPhone.Text;
        eContact.MobilePhone = txtMobile.Text;
        eContact.Fax = txtFax.Text;
        eContact.Active = ckActive.Checked;
        eContact.SendNewsletter = ckReceiveNewsLetter.Checked;

        try
        {
            eContact.ContactVisitDate = Convert.ToDateTime(txtVisitDate.Text);
            lblWrongFormat.Visible = false;
            lblWrongFormatStar.Visible = false;
        }
        catch 
        {
            lblWrongFormat.Visible = true;
            lblWrongFormatStar.Visible = true;
            return;
        }        
        eContact.Save();

        if (isNew) 
        {
            CreateEmailAndSend(eContact.ContactId);
        }


        if (!eContact.Active) 
        {
            ContactGroupMemberCollection cContactGroupMembers = new ContactGroupMemberCollection();
            IPredicateExpression filterContactGroupMember = new PredicateExpression();
            filterContactGroupMember.Add(ContactGroupMemberFields.ContactId == eContact.ContactId);
            cContactGroupMembers.DeleteMulti(filterContactGroupMember);
        }

        // save extra fields
        for (int i = 0; i < grdFields.Rows.Count; i++) 
        {
            ContactFieldEntity eContactField = new ContactFieldEntity();
            eContactField.ContactId = eContact.ContactId;
            eContactField.ContactPageFieldId = Convert.ToInt32(((TextBox)grdFields.Rows[i].Cells[2].FindControl("id")).Text);
            switch (Convert.ToInt32(grdFields.Rows[i].Cells[1].Text)) 
            {
                case Parameters.TEXTBOX_TYPE:
                case Parameters.DATETIME_TYPE:
                case Parameters.TEXTAREA_TYPE:
                    eContactField.FieldValue = ((TextBox)grdFields.Rows[i].Cells[1].Controls[0]).Text;
                    break;
                case Parameters.COMBOBOBOX_TYPE:
                    eContactField.FieldValue = ((DropDownList)grdFields.Rows[i].Cells[1].Controls[0]).SelectedValue;
                    break;
                case Parameters.CHECKBOX_TYPE:
                    eContactField.FieldValue = ((CheckBox)grdFields.Rows[i].Cells[1].Controls[0]).Checked.ToString();
                    break;
            }

            eContactField.Save();
        }


        for (int i = 0; i < Request.Files.Count; i++) 
        {
            if (Request.Files[i].FileName != "")
            {

                lblFileExist.Visible = false;
                ContactFileEntity eContactFile = new ContactFileEntity();
                eContactFile.ContactId = eContact.ContactId;
                eContactFile.File = Request.Files[i].FileName;
                eContactFile.ServerFile = Methods.UploadFile(Request.Files[i], MapPath("UploadedFiles"));
                string[] vars = eContactFile.ServerFile.Split('\\');
                eContactFile.FileUrl = PageName() + "UploadedFiles/" + vars[vars.Length - 1];
                eContactFile.Save();
            }
        }


        LoadFiles(eContact.ContactId);
        lblSavedContact.Visible = true;
        //Response.Redirect("ContactList.aspx");
    }

    private string PageName()
    {
        string url = Request.Url.AbsoluteUri;
        string[] fragments = url.Split('/');
        return url.Replace(fragments[fragments.Length - 1], "");
    }

    #endregion user interface

    #region actions


    private void ModifyContact()
    {
        Response.Redirect("ContactList.aspx");
    }
    #endregion actions

    protected void LoadFieldsForContactType(object sender, EventArgs e)
    {
        ShowExtraFields(Convert.ToInt32(cmbContactTypes.SelectedValue));
    }


    /// <summary>
    ///  get fields to be filled in
    /// </summary>
    /// <param name="contactTypeId"></param>
    /// <returns></returns>
    private DataTable Fields(int contactTypeId) 
    {
        DataTable dtFields = new DataTable();
        
        ResultsetFields fields = new ResultsetFields(7);
        fields.DefineField(AvailableToContactTypeFieldIndex.ContactTypeId, 0, "ContactTypeId");
        fields.DefineField(ContactPageFieldFieldIndex.Name, 1, "Name");
        fields.DefineField(ContactPageFieldFieldIndex.Type, 2, "Type");
        fields.DefineField(ContactPageFieldFieldIndex.OrderIndex, 3, "OrderIndex");
        fields.DefineField(ContactPageFieldFieldIndex.ContactPageFieldId, 4, "ContactPageFieldId");
        fields.DefineField(ContactPageFieldFieldIndex.Rows, 5, "Rows");
        fields.DefineField(ContactPageFieldFieldIndex.Columns, 6, "Columns");

        RelationCollection relations = new RelationCollection();
        relations.Add(ContactPageFieldEntity.Relations.AvailableToContactTypeEntityUsingContactPageFieldId);
        
        IPredicateExpression filter = new PredicateExpression();
        filter.Add(AvailableToContactTypeFields.ContactTypeId == contactTypeId);

        TypedListDAO dao = new TypedListDAO();
        SortExpression sortExp = new SortExpression(new SortClause(fields["OrderIndex"], SortOperator.Ascending));
        dao.GetMultiAsDataTable(fields, dtFields, 0, sortExp, filter,relations, false, null, null, 0, 0);

        return dtFields;
    }

    /// <summary>
    /// remove file attached to a contract
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ContactFileCommand(object sender, GridViewCommandEventArgs e)
    {
        if (((System.Web.UI.WebControls.Button)(e.CommandSource)).Text == "Remove") 
        {
            try
            {
                int contactFileId = Convert.ToInt32(e.CommandArgument);                
                ContactFileEntity eContactFile = new ContactFileEntity(contactFileId);
                int contactId = eContactFile.ContactId;

                if (File.Exists(eContactFile.ServerFile))
                {
                    File.Delete(eContactFile.ServerFile);
                }

                eContactFile.Delete();

                LoadFiles(contactId);
            }
            catch { }

        }
    }


    private static void CreateEmailAndSend(int contactId)
    {
        string strSMTP = ConfigurationManager.AppSettings["SmtpServer"];
        string strMailFrom = ConfigurationManager.AppSettings["MailFrom"];


        WelcomeTemplateCollection cWelcomeTemplates = new WelcomeTemplateCollection();
        cWelcomeTemplates.GetMulti(null);

        if (cWelcomeTemplates.Count != 1)
        {
            return;
        }
        else
        {
            TemplateCollection cTemplates = new TemplateCollection();
            IPredicateExpression filter = new PredicateExpression();
            filter.Add(TemplateFields.TemplateId == cWelcomeTemplates[0].TemplateId);
            cTemplates.GetMulti(filter);

            if (cTemplates.Count == 1)
            {
                string template = cTemplates[0].Template;
                if (cTemplates[0].FilePath != "")
                {
                    template = "<img src=\"" + cTemplates[0].FileUrl + "\" border=0><br> " + template;
                }
                template = "'" + template + "'";

                // call - for all users in a group create a phone call
                SqlConnection conn = new SqlConnection(DbUtils.ActualConnectionString);
                conn.Open();
                SqlCommand cmd = new SqlCommand(@"select * from vTemplate", conn);

                try
                {
                    SqlDataReader sdr = cmd.ExecuteReader();
                    DataTable dt = sdr.GetSchemaTable();
                    sdr.Close();

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        template = template.Replace("[" + dt.Rows[i][0] + "]", "'+[" + dt.Rows[i][0] + "]+'");
                    }
                    cmd = new SqlCommand(@"select EmailAddress," + template + ",ContactId from Contact where ContactId=" + contactId.ToString(), conn);
                    sdr = cmd.ExecuteReader();

                    while (sdr.Read())
                    {
                        //sdr.Read();

                        //MailMessage mail = new MailMessage(sdr.GetValue(0).ToString(), sdr.GetValue(0).ToString());
                        MailMessage mail = new MailMessage(strMailFrom, sdr.GetValue(0).ToString());

                        mail.Body = sdr.GetValue(1).ToString();
                        mail.IsBodyHtml = true;
                        mail.Subject = "Welcome";

                        //SmtpClient client = new SmtpClient("smtp.rdslink.ro");
                        SmtpClient client = new SmtpClient(strSMTP);
                        try
                        {
                            client.Send(mail);
                            mail.Dispose();
                        }
                        catch {}
                        finally{}
                    }
                    sdr.Close();
                }
                catch {}
                conn.Dispose();
            }
        }
    }

    protected void validateName_ServerValidate(object source, ServerValidateEventArgs args)
    {        
        args.IsValid = true;
        if (Page.IsPostBack && !String.IsNullOrEmpty(Request.QueryString["id"]))
        {
            return;
        }

        ContactCollection cContact = new ContactCollection();
        IPredicateExpression filterContactName = new PredicateExpression();
        filterContactName.Add(ContactFields.Name == txtName.Text.ToUpper());
        if (cContact.GetDbCount(filterContactName) > 0)
        {
            args.IsValid = false;   
        }      
    }
}


